﻿package tk.mystudio.web.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.util.AntUrlPathMatcher;
import org.springframework.security.web.util.UrlMatcher;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import tk.mystudio.permission.bean.Role;
import tk.mystudio.permission.constant.RoleType;
import tk.mystudio.permission.service.RoleService;


@Service("accessDecisionManager")
public class AccessDecisionManager implements
		org.springframework.security.access.AccessDecisionManager {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(AccessDecisionManager.class);
	
	private UrlMatcher urlMatcher = new AntUrlPathMatcher();
	//超级管理员
	private static Collection<GrantedAuthority> superAdmin = new ArrayList<GrantedAuthority>();
	//匿名资源，如登录页面
	private List<String> anonymousResource = new ArrayList<String>();
	//认证资源，如菜单页面
	private List<String> authorizationResource = new ArrayList<String>();	
	
	@Resource
	private RoleService roleService;
	
	public void init() {
		//TODO 考虑在roleService中添加一个方法
		for(Role role : roleService.getAllRoles()) {
			if(role.getRoleType()==RoleType.BUILT_IN_ROLE) {
				superAdmin.add(new GrantedAuthorityImpl(role.getName()));
			}
		}
		if(superAdmin.isEmpty()) {
			logger.info("注意：系统未配置超级管理员角色！！！");
		} else {
			logger.info("====================== 超级管理员 ========================");
			logger.info(superAdmin);
			logger.info("=========================================================");
		}
	}
	
	/**
	 * 去掉URL后的参数
	 * @param url
	 * @return
	 */
	private String dropParams(String url) {
		if(StringUtils.hasText(url)) {
			int index = url.indexOf("?");
			if(index!=-1) {
				return url.substring(0, index);
			}
			return url;
		}
		return "";
	}
	
	// In this method, need to compare authentication with configAttributes.
	// 1, A object is a URL, a filter was find permission configuration by this
	// URL, and pass to here.
	// 2, Check authentication has attribute in permission configuration
	// (configAttributes)
	// 3, If not match corresponding authentication, throw a
	// AccessDeniedException.
	public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		for(GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
			if(superAdmin.contains(grantedAuthority)) {
				return;
			}
		}
		
		String url = dropParams(((FilterInvocation) object).getRequestUrl());
		//匿名资源都可以访问
		for(String anonymousURL : anonymousResource) {
			if (urlMatcher.pathMatchesUrl(anonymousURL, url)) {
				return;
			}
		}

		//认证资源仅登录用户可以访问
		if(authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken)) {
			for(String anonymousURL : authorizationResource) {
				if (urlMatcher.pathMatchesUrl(anonymousURL, url)) {
					return;
				}
			}
		}
		
		if (configAttributes == null || configAttributes.isEmpty()) {
			if (logger.isDebugEnabled()) {
				logger.debug("decide(Authentication, Object, Collection<ConfigAttribute>) - end"); //$NON-NLS-1$  
			}
			throw new AccessDeniedException("未明确分配权限的资源仅内置管理员可以访问");
		}
		logger.info("正在访问的url是：" + url);
		
		Iterator<ConfigAttribute> ite = configAttributes.iterator();
		while (ite.hasNext()) {
			ConfigAttribute ca = ite.next();
			logger.info("needRole is：" + ca.getAttribute());
			String needRole = ((SecurityConfig) ca).getAttribute();
			for (GrantedAuthority ga : authentication.getAuthorities()) {
				logger.info("\t授权信息是：" + ga.getAuthority());
				if (needRole.equals(ga.getAuthority())) { // ga is user's role.
					if (logger.isDebugEnabled()) {
						logger.info("判断到，needRole 是" + needRole + ",用户的角色是:"
								+ ga.getAuthority() + "，授权数据相匹配");
						logger.info("decide(Authentication, Object, Collection<ConfigAttribute>) - end"); //$NON-NLS-1$  
					}
					return;
				}
			}
		}
		throw new AccessDeniedException("没有权限");
	}

	public boolean supports(ConfigAttribute attribute) {
		// TODO Auto-generated method stub
		return true;
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}
	
	public void setAnonymousResource(List<String> anonymousResource) {
		this.anonymousResource = anonymousResource;
	}
	
	public void setAuthorizationResource(List<String> authorizationResource) {
		this.authorizationResource = authorizationResource;
	}
	
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}
}
